#!/bin/sh

# Copyright 2018 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

# Simple script used to regenerate zip files used for unit-testing the
# crazy linker zip parser. This outputs a fragment of C code through 'xdd'
# on Linux that can be copied into crazy_linker_zip_test_data.cpp directly.

set -e

PROGNAME=$(basename "$0")

die () {
  echo "ERROR: $@"
  exit 1
}

TMP_DIR=/tmp/zip-files-tmp-$$
OUTPUT_DIR=/tmp/zip-files

generate_c_source () {
  # Turn generated table const, it's cleaner.
  # Also indent with 4 spaces (Chromium style).
  xxd -i $1 | \
    sed -e 's/^unsigned/const unsigned/g' | \
    sed -e 's/^  0x/    0x/g'
}

# Preparing temporary directory.
mkdir -p $TMP_DIR
rm -rf $TMP_DIR/*
cd $TMP_DIR

cat <<EOF
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// AUTO-GENERATED BY $PROGNAME - DO NOT EDIT!!

#include "crazy_linker_zip_test_data.h"

namespace crazy {
namespace testing {

EOF

printf "// An empty zip archive\n"
touch empty_file
zip -q empty_archive empty_file
zip -q -d empty_archive empty_file 2>/dev/null
generate_c_source empty_archive.zip
printf "\n"

printf "// A zip archive with a single file named 'hello_world.txt' that\n"
printf "// contains the bytes for 'Hello World Hello World\\\n' without\n"
printf "// compression.\n"
echo "Hello World Hello World" > hello_world.txt
zip -q -0 hello.zip hello_world.txt
generate_c_source hello.zip
printf "\n"

printf "// The same zip archive, but with the file stored compressed.\n"
zip -q -9 hello_compressed.zip hello_world.txt
generate_c_source hello_compressed.zip
printf "\n"

LIB_SUBDIR=lib/test-abi
LIB1_NAME=libfoo.so
LIB2_NAME=crazy.libbar.so
LIB1_TEXT="This is the first test library!"
LIB2_TEXT="This is the second test library!"
cat <<EOF
// A zip archive with two uncompressed files under $LIB_SUBDIR/
// named '$LIB1_NAME' and '$LIB2_NAME', with the following data:
// - first lib:  '$LIB1_TEXT'
// - second lib: '$LIB2_TEXT'
EOF
mkdir -p $LIB_SUBDIR
printf "This is the first test library!" > $LIB_SUBDIR/$LIB1_NAME
printf "This is the second test library!" > $LIB_SUBDIR/$LIB2_NAME
zip -q -0 lib_archive.zip $LIB_SUBDIR/$LIB1_NAME $LIB_SUBDIR/$LIB2_NAME
generate_c_source lib_archive.zip

cat <<EOF

}  // namespace testing
}  // namespace crazy
EOF

rm -rf $TMP_DIR
